from google.appengine.ext import webapp
from google.appengine.api import memcache

import settings
from helper import template
from model import comments

#debug
if (settings.DEBUG):
    from helper import cron


class Handler(webapp.RequestHandler):
    def prepareComments(self, comments):
        items = comments['items']
        for index in range(len(items)):
            items[index]['entry_content'] = items[index]['entry_content'].replace('<br/>', '\n')
        return comments

    def get(self):
        main_html = memcache.get('main_html')
        
        #debug
        if (settings.DEBUG):
            main_html = False
            cron.main()
        
        if not main_html:
            params = settings.HTML_PARAMS
            main_key = 'debug' if settings.DEBUG else 'app'
            params.update({
                'content': template.get('templates/livehabr.html',
                                        self.prepareComments(comments.get())),
                'add_css': template.getCss(settings.MAIN_CSS[main_key],
                                       settings.STATIC_URL[main_key]),
                'add_js': template.getJs(settings.MAIN_JS[main_key],
                                          settings.STATIC_URL[main_key]),
            })
            main_html = template.get('templates/index.html', params)
            memcache.add('main_html', main_html)

        self.response.out.write(main_html)